//
//  YWSystemWebViewController.m
//  DoneTask
//
//  Created by NeiQuan on 16/8/10.
//  Copyright © 2016年 Mr-yuwei. All rights reserved.
//

#import "YWSystemWebViewController.h"
#import "YWStaticPublicHeader.h"
#import "YWHeader.h"
//#import "JJSDK.h"
//#import "JJDiamondConstants.h"
@interface YWSystemWebViewController ()<UIWebViewDelegate,NJKWebViewProgressDelegate>
{
    UIWebView                *_webview;
    NJKWebViewProgressView   *_progressView;
    NJKWebViewProgress       *_progressProxy;
}
@end

@implementation YWSystemWebViewController
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self SetUPuserConfig];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets=NO;
    self.title=@"省钱买";
    [self addObserver];//添加监听
    [self makecontentWebView];
  
}
-(void)addObserver
{
    __weak typeof(self)weakself=self;
    [[ NSNotificationCenter defaultCenter] addObserver:weakself selector:@selector(openWebView) name:@"haveLogin" object:nil];
    [[ NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showalert) name:@"alertNotice" object:nil];

}
-(void)SetUPuserConfig{
    
    UIWindow *window=[ UIApplication sharedApplication].keyWindow;
    for (UIView *view   in window.subviews )
    {
        if ([view isKindOfClass:[ UIAlertView class]])
        {
            [view  removeFromSuperview];
        }
    }
    if ([ NSString StringIsNULL:[ NSString idfa]])
    {
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"省钱买a要访问你的广告跟踪,否则会影响正常的使用!请在设置->隐私->广告,关闭限制广告跟踪权限" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alert show];
        
    }else{
        
        if (![[ NSUserDefaults standardUserDefaults] boolForKey:userlogin])//不知道能否被注册
        {
            NSDictionary *parameters=@{@"deviceBrand":@"苹果手机",@"deviceModel":[NSString phoneModel],@"idfa":[ NSString idfa],@"ip":[NSString getIPAddress],@"mac":[NSString  macaddress],@"network":@([ NSString getNetWorkStates]),@"openudid":[ NSString  createUUID],@"systemVersion":[NSString deviceVersion],@"type":@"1",@"imei":@""};
            [GoodListDataManger  netWorkGetWithDataType:NetworkDatalaunchType parameters:parameters SuccessBlock:^(NSDictionary *dic)
             {
                 if ([dic[@"code"]integerValue]==0)//创建用户成功   //每次进入APP时都需要调用，创建成功则返回唯一新设备Id，失败返回旧设备Id
                 {
                     [[ NSUserDefaults standardUserDefaults] setObject:[dic[@"response"] stringValue] forKey:userId];//保存用户id
                     [[ NSUserDefaults standardUserDefaults] synchronize];
                     [[ NSUserDefaults standardUserDefaults] setBool:YES forKey:userlogin];
                     [[ NSNotificationCenter defaultCenter] postNotificationName:@"haveLogin" object:nil];//告诉用户已经可以启动
                   // [JJSDK requestJJSession:@"223efb0b3c2d73877e3fd49bba90db14" withUserID:[dic[@"response"] stringValue]];
                 }
                 
             }];
        }
    }
}
-(void)showalert{
    
    if ([ NSString StringIsNULL:[ NSString idfa]])
    {
        UIAlertView *alert=   [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"省钱买a要访问你的广告跟踪,否则会影响正常的使用!请在设置->隐私->广告,关闭限制广告跟踪权限" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alert show];
        
    }
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex!=0)
    {
        NSURL *url = [NSURL URLWithString:@"prefs:root=Privacy"];
        if ([[UIApplication sharedApplication] canOpenURL:url])
        {
            [[UIApplication sharedApplication] openURL:url];
        }
        
    }
}
#pragma mark --创建webView
-(void)makecontentWebView
{
    __weak typeof(self)wakself=self;
    UIWebView *webview=[[ UIWebView alloc] initWithFrame:CGRectMake(0, 0, YWWidth, YWHeight-64)];
    [webview setBackgroundColor:[ UIColor clearColor]];
    _webview=webview;
    _progressProxy = [[NJKWebViewProgress alloc] init];
    webview.delegate = _progressProxy;
    _progressProxy.webViewProxyDelegate = self;
    _progressProxy.progressDelegate = self;
    
    CGFloat progressBarHeight = 2.f;
    CGRect barFrame = CGRectMake(0, 46 - progressBarHeight,YWWidth, progressBarHeight);
    _progressView = [[NJKWebViewProgressView alloc] initWithFrame:barFrame];
    [_progressView.progressBarView setBackgroundColor:[ UIColor colorWithString:@"#F4AE25"]];
    _progressView.progress=0.0;
    _progressView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    [self.navigationController.navigationBar addSubview:_progressView];
    [self.view addSubview:webview];
    UIButton *btn=[ UIButton buttonWithType:UIButtonTypeCustom];
    [btn setFrame:CGRectMake(0, 0, 25, 25)];
    [btn setBackgroundImage :[ UIImage imageNamed:@"刷新"] forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem=[[ UIBarButtonItem alloc] initWithCustomView:btn];
    [btn addTarget:wakself action:@selector(clickrefresh) forControlEvents:UIControlEventTouchUpInside];
}
//-(void)clickrefresh
//{
//     [JJSDK showJJDiamondWithViewController:self];
//     [JJSDK setDelegate:self];//设置代理方法
//    
//    
//}
-(void)openWebView
{
    
    NSString *string=[[ NSUserDefaults standardUserDefaults] objectForKey:userId];
    if (![ NSString StringIsNULL:string]&&![NSString StringIsNULL: [ NSString idfa]])
    {
        NSString *version = [[[NSBundle mainBundle] infoDictionary]objectForKey:@"CFBundleShortVersionString"];//获取版本号
        NSLog(@"yuwei13%@",version);
        NSDictionary *parameters=@{@"id":string,@"clientVersion":version,@"type":@"1"};
        [GoodListDataManger  netWorkGetWithDataType:NetworkDatasystemOpentype parameters:parameters SuccessBlock:^(NSDictionary *dic){
            if ([dic[@"code"]integerValue]==0)
            {
                if ([dic[@"response"][@"iosAllowFullFunction"]integerValue]==1)//http://1515.cn:8080/yproject/api/
                {
                    //http://www.neiquan.net:8113/yproject/h5/html/index.jsp?type=1&idfa=%@
                  //  [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[ NSString stringWithFormat:@"http://1515.cn:8080/yproject/h5/html/index.jsp?type=1&idfa=%@",[ NSString idfa]]]];
                    [_webview  loadRequest:[ NSURLRequest requestWithURL:[ NSURL URLWithString:[ NSString stringWithFormat:@"http://1515.cn:8080/yproject/h5/html/index.jsp?type=1&idfa=%@",[ NSString idfa]]]]];
                    
                }
            }
        }];
        
    }
}
- (void)webViewProgress:(NJKWebViewProgress *)webViewProgress updateProgress:(float)progress{
    
    [_progressView setProgress:progress animated:YES];
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView{
    
    [self showMBProgressHUDLoadinginView:self.view ];
    
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    
    [self removeMBProgressView];
    
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:( NSError *)error{
    
    [self removeMBProgressView];
    
    [self showMBProgressHUDNetErrorMessage:@"加载失败,请查看你的网络" inView:self.view];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//*************************************************//

/**
 *  减分成功
 *
 *  @param JJPointsAmounts 最新余额
 *  @param currencyName      分数类型
 */
- (void)spendJJPointsSuccess:(int)JJPointsAmounts currency:(NSString *)currencyName{
    
    
}
/**
 *  减分失败
 *
 *  @param error 失败原因描述
 */
- (void)spendJJPointsFail:(NSError *)error{
    
    
}
/**
 *  加分成功
 *
 *  @param JJPointsAmounts 最新余额
 *  @param currencyName      分数类型
 */
- (void)awardJJPointsSuccess:(int)JJPointsAmounts currency:(NSString *)currencyName{
    
}


/**
 *  加分失败
 *
 *  @param error 失败原因描述
 */
- (void)awardJJPointsFail:(NSError *)error{
    
}
/**
 *  获取用户当前分数成功
 *
 *  @param JJPointsAmounts 最新余额
 *  @param currencyName      分数类型
 */
- (void)getUserJJPointsSuccess:(int)JJPointsAmounts currency:(NSString *)currencyName{
    
}
/**
 *  获取用户当前分数失败
 *
 *  @param error 失败原因描述
 */
- (void)getUserJJPointsFail:(NSError *)error{
    
}
/**
 *  取回开发者自定义参数成功
 *
 *  @param param 参数值
 */
- (void)fetchParameterDefineByDeveloperSuccess:(NSString *)param
{
    
    
}
/**
 *  取回开发者自定义参数失败
 *
 *  @param error 失败原因描述
 */
- (void)fetchParameterDefineByDeveloperFail:(NSError *)error{
    
    
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
